import datetime
import hashlib
import json
import time
from typing import Dict, List, AnyStr
import requests
import pandas as pd
from createDataByInsert.otherClass.catchRequest import CatchRequest, reqBase
from createDataByInsert.utils import myTime
from pandas import DataFrame
from pymysql.cursors import Cursor, DictCursor
from requests import Session
from sqlite3 import Connection
from utils.common_dcc import response_time
from utils.environments_json import json_data, urlHead
from setupDemo import login_session_mid
# env=json_data.get(json_data.get("current_env")).get("server")
sessionList=[]

# 获取验证码登录的session
def getLoginSession(source,phone,loginType)->Session:
    session,userId=login_session_mid(phone=phone,source=source,loginType=loginType)
    session.headers["userId"] = str(userId)
    sessionList.append(session)
    return session


# 获取md5加密后的首字符
def md5valueHeader(key:str):

    input_name = hashlib.md5()

    input_name.update(key.encode("utf-8"))

    return input_name.hexdigest()[0:1]


def selectPhoneInSqlite(tag:str,sqliteConnet:Connection)->int:
    selectSql='select phone from user_info where tag="%s"'%(tag)
    cur=sqliteConnet.cursor()
    cur.execute(selectSql)
    phone=cur.fetchone()[0]
    return int(phone)



def getBackSession(userId:str)->Session:
    headers = {"Content-Type": "application/json;charset=utf-8"}
    headers["u"]=userId
    headers["source"]="ADMIN"
    session = requests.session()
    session.headers.update(headers)
    return session



# dataDic的数据结构{"骆峰式的字段名":接口传参时对应的值}
def interfaceDataValidate(table:str, value, mysqlCursor:Cursor, interfaceDataDic:Dict=None, extraDataDic:Dict[str, str]=None, prop=None):
    propList = []
    propStr = ""
    mysqlCursor.execute("desc %s" % (table))
    desc = mysqlCursor.fetchall()
    L = []
    for i in desc:
        L.append(i[0])

    merDic={}
    if interfaceDataDic != None and interfaceDataDic != {}:
        merDic.update(interfaceDataDic)

    if extraDataDic != None and extraDataDic != {}:
        merDic.update(extraDataDic)


    if merDic != None and merDic != {}:
        for key in merDic.keys():
            turnStr=turnCharacter(key)
            if turnStr in L:
                propList.append(turnStr)
                propStr = propStr + turnStr + ","

    if propStr!="":
        propStr=propStr[:-1]
    if prop is None:
        sqlStr="select "+propStr+" "+"from "+table+" where id=%s;"%(value)
    else:
        sqlStr = "select " + propStr + " " + "from " + table + " where %s=%s;" % (prop, value)
    mysqlCursor.execute(sqlStr)
    selectRes=mysqlCursor.fetchone()
    for colIndex in range(len(selectRes)):
        tableValue=selectRes[colIndex]
        interfaceValue=merDic[turnCharacter(propList[colIndex])]
        if type(interfaceValue) is bool:
            if interfaceValue==True and tableValue not in [b'\x01',1,True,"1",1.0]:
                return "表中的值：" + tableValue + "   与   接口参数值：" + interfaceValue + ",不相等！"
            elif interfaceValue==False and tableValue not in [b'\x00',0,False,"0",0.0]:
                return "表中的值：" + tableValue + "   与   接口参数值：" + interfaceValue + ",不相等！"
        elif type(interfaceValue) is str:
            if type(tableValue) is not str:
                tableValue=str(tableValue)
            if tableValue!=interfaceValue:
                return "表中的值："+tableValue+"   与   接口参数值："+interfaceValue+",不相等！"

        elif type(interfaceValue) is int:
            if type(tableValue) is datetime.datetime:
                tableValue=int(time.mktime(tableValue.timetuple()) * 1000.0 + tableValue.microsecond / 1000.0)
            elif type(tableValue) is not int:
                tableValue=0 if tableValue is None else tableValue
                tableValue=int(tableValue)
            if tableValue!=interfaceValue:
                return "表中的值："+str(tableValue)+"   与   接口参数值："+str(interfaceValue)+",不相等！"

        elif type(interfaceValue) is float:
            if type(tableValue) is not float:
                tableValue=0 if tableValue is None else tableValue
                tableValue=float(tableValue)
            if tableValue!=interfaceValue:
                return "表中的值："+str(tableValue)+"   与   接口参数值："+str(interfaceValue)+",不相等！"
        elif type(interfaceValue) is dict or type(interfaceValue) is list :
            tableValue=json.loads(tableValue)
            if tableValue!=interfaceValue:
                return "表中的值："+str(tableValue)+"   与   接口参数值："+str(interfaceValue)+",不相等！"

        elif interfaceValue is None:
            if tableValue!=interfaceValue:
                return "表中的值："+str(tableValue)+"   与   接口参数值：None"+",不相等！"
        else:
            return "不支持检验该接口的参数 %s 值 %s，只支持:bool ,str,int,float,dict。"%(turnCharacter(propList[colIndex]),interfaceValue)
    return True


def addToListInDic(dic:Dict[str,List],key:str,value):
    if key not in dic.keys():
        L = []
        L.append(value)
        L.sort()
        dic[key]=L
    else:
        dic[key].append(value)
        t = set(dic[key])
        dic[key]=list(t)
        dic[key].sort()


# 将骆峰式字符串与下划线的字符串相互转换
def turnCharacter(str:str):
    result = ""
    if "_" not in str:
        for i in str.replace(str[0], str[0].lower()):
            result += '_{}'.format(i.lower()) if i.isupper() else i
    else:
        tmpStr=""
        turnUpper = False
        for i in range(len(str)):
            if str[i]!="_":
                if turnUpper==False:
                    tmpStr+=str[i]
                else:
                    tmpStr+=str[i].upper()
                    turnUpper = False
            else:
                turnUpper=True
        result=tmpStr
    return  result


# 把请求抽象成一个公共方法
# argsPostion: {"uri":"dict","body":"str"}
def reqMethod(uri:AnyStr,data:str,session:Session,method:str,argsPosition:dict,L:list=None):
    resDic, res=reqBase(urlHead,uri,data,session,method,argsPosition,L)
    response_time(uri, res)
    return resDic,res



def circleSelect(data,itor:iter,replacedStr:str="动态获取"):
    if type(data) is list and data is not None:
        for i in range(len(data)):
            if type(data[i]) is list or type(data[i]) is dict:
                circleSelect(data[i],itor,replacedStr=replacedStr)
                continue
            if data[i]==replacedStr:
                data[i]=next(itor)

    if type(data) is dict and data is not None:
        for j in data.keys():
            if type(data[j]) is list or type(data[j]) is dict:
                circleSelect(data[j],itor,replacedStr=replacedStr)
                continue
            if data[j]==replacedStr:
                data[j]=next(itor)
    return data


def addDataToExcle(data:DataFrame,excelPath,sheetName):
    df = pd.read_excel(excelPath,sheet_name=sheetName)
    df_new = pd.concat([df,data], ignore_index=True)
    df_new.to_excel(excelPath, sheet_name=sheetName, index=False, engine="openpyxl")


def getRealDay():
    my_time = myTime()
    studyDate = my_time.getTestTimeBeforeNow(days=0)
    today3 = studyDate.split(" ")[0] + " 03:00:00"
    if studyDate < today3:
        realDay = my_time.getTestTimeBeforeNow(days=1).split(" ")[0]
    else:
        realDay = studyDate.split(" ")[0]
    return realDay



def setOthersUserIdCanceled(userCenterMysqlCon,userList):
    con:Connection=userCenterMysqlCon[1]
    curDic: Cursor = con.cursor(cursor=DictCursor)
    if(len(userList)==1):
        sql="update user_login_record set sys_id=9898 where sys_id=6 and user_id !={}".format(userList[0])
    elif (len(userList)>=1):
        sql="update user_login_record set sys_id=9898 where sys_id=6 and user_id not in {}".format(tuple(userList))
    curDic.execute(sql)
    con.commit()


def setOthersUserIdNormal(userCenterMysqlCon,userList):
    con:Connection=userCenterMysqlCon[1]
    curDic: Cursor = con.cursor(cursor=DictCursor)
    if(len(userList)==1):
        sql="update user_login_record set sys_id=6 where sys_id=9898 and user_id !={}".format(userList[0])
    elif (len(userList)>=1):
        sql="update user_login_record set sys_id=6 where sys_id=9898 and user_id not in {}".format(tuple(userList))
    curDic.execute(sql)
    con.commit()

if __name__=="__main__":
    pass




